package com.melon.utils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public final class GSON {

    private static final Logger logger = LoggerFactory.getLogger(GSON.class);
    private static final Gson defalutGson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();

    public static String toJson(Object src) {
        try {
            return defalutGson.toJson(src);
        } catch (Exception e) {
            logger.error("无法将对象转为JSON." + src);
            return "";
        }
    }

    public static <T> T fromJson(String json, Class<T> classOfT) {
        if (json == null || json.trim().isEmpty()) return null;
        try {
            return defalutGson.fromJson(json, classOfT);
        } catch (Exception e) {
            logger.error("无法将json转为对象. (json=" + json + ")");
            return null;
        }
    }

    public static String getPropertyAsString(JsonObject json, String memberName) {
        JsonElement element = json.get(memberName);
        if (element != null) {
            return element.getAsString();
        }
        return "";
    }

    public static String getObjectAsString(JsonObject json, String memberName) {
        JsonElement element = json.get(memberName);
        if (element != null && element.isJsonObject()) {
            return element.getAsJsonObject().toString();
        }
        return "";
    }
}
